# 模拟AURO仪器
# 参考数据 raw_data\课题3\AURO\Aurora4000 2018-11-27.txt
# 自动变化数据：
# 日期时间; 635nm总散射系数; 525nm总散射系数; 450nm总散射系数

import parse
import fire
import time
import datetime
import os
import random
import regex as re
from math import sin

# 输出log，便于调试
import logging


def update_data_dict_gen(t=None,mode='sin',selected_cols=None,data_types=None):
    """假造一些数据，返回字典格式
    """
    now_ts = time.time() if t is None else t # 默认当前时间
    update_data_dict = {}
    
    # 时间处理
    now_datetime = datetime.datetime.fromtimestamp(now_ts)
    update_data_dict['yyyy'] = now_datetime.year
    update_data_dict['MM'] = now_datetime.month
    update_data_dict['dd'] = now_datetime.day
    update_data_dict['hh'] = now_datetime.hour
    update_data_dict['mm'] = now_datetime.minute
    update_data_dict['ss'] = now_datetime.second


    # 生成数据
    if mode == 'sin':
        # 正弦变化的数据
        period = 100 # s
        shift = 10 # s
        for i,col in enumerate(selected_cols):
            if data_types[col] == 'f':
                update_data_dict[col] = 1000*(2+sin((now_ts+shift*i)/period))
            elif data_types[col] == 'd':
                update_data_dict[col] = int(1000*(1+sin((now_ts+shift*i)/period)))
            else :
                raise RuntimeError(f'unknown data type {col}:{data_types[col]}')
    elif mode == 'random':
        # 随机数据
        max = 1.0
        min = 0.0
        for i,col in enumerate(selected_cols):
            update_data_dict[col] = random.random()*(max-min)+min
    else:
        raise RuntimeError(f'mode={mode}, it must be "sin" or "random"')
    return update_data_dict

def main(output_filename= None,
        delay_time = 0.95,
        test_mode=False,
        max_time_hours = 24,
        mode='sin',
        log_level = 'INFO'):
    """假造一些输出到log文件，模拟实际设备
    """
    # 初始化
    logging.basicConfig(level = getattr(logging,log_level.upper(),logging.INFO)) # 默认info
    file_base_name = os.path.basename(__file__)
    logger = logging.getLogger(file_base_name)

    # 分隔符
    sep = ', '
    # 列名
    ## 33个
    col_names = 'dd,MM,yyyy,hh,mm,ss'.split(',')

    for angle in 'total,0,10,30,50,70,90'.split(','):
        for wavelength in [635,525,450]:
            col_names.append(f'sc_{wavelength}_{angle}')

    col_names += 'sample_air_temp,chassis_temp,RH,pressure,status1,status2'.split(',')
    # 默认值，为保持完整性
    defaults_str = '27/11/2018 08:13:30, 30.135, 31.907, 33.610, 27.750, 33.919, 31.836, 18.111, 21.656, 21.258, 15.053, 14.174, 14.797, 12.460, 9.788, 10.946, 9.387, 9.268, 9.021, 7.812, 7.815, 9.404, 4.078, 0.633, 6.951, 995.110, 00, 07'
    
    data_write_formats = '02d,02d,04d,02d,02d,02d'.split(',')+['.3f']*25+['2d']*2
    data_read_formats = [format[-1] for format in data_write_formats]

    # data types
    data_types = dict(zip(col_names, data_read_formats))

    # selected cols
    selected_cols = [col.strip() for col in 'sc_635_total,sc_525_total,sc_450_total'.split(',') ]

    # 生成格式化字符串
    datetime_formatter = '{dd:02d}/{MM:02d}/{yyyy:04d} {hh:02d}:{mm:02d}:{ss:02d}'
    line_write_formatter=datetime_formatter +sep + sep.join([f'{{{col_name}:{format}}}' for col_name,format in zip(col_names[6:],data_write_formats[6:])])
    logger.info(line_write_formatter)

    datetime_formatter = '{dd:d}/{MM:d}/{yyyy:d} {hh:d}:{mm:d}:{ss:d}'
    line_read_formatter=datetime_formatter +sep + sep.join([f'{{{col_name}:{format}}}' for col_name,format in zip(col_names[6:],data_read_formats[6:])])
    logger.info(line_read_formatter)

    # 简单测试
    parse_result = parse.parse(line_read_formatter,defaults_str)
    logger.info(parse_result)
    if parse_result is None:
        raise RuntimeError('Something go wrong!')

    # 默认值
    data_dict_defaults = parse_result.named
    
    # 输出文件名
    output_filename = output_filename if output_filename is not None else (file_base_name+r".test.log")
    with open(output_filename,'w+',encoding='utf-8') as OF:
        if test_mode: OF = None
        #no header
        #data lines
        start_time = time.time()
        while(time.time()<start_time + max_time_hours*24*3600): # max hours
            data_dict = data_dict_defaults
            update_data_dict = update_data_dict_gen(mode=mode,selected_cols=selected_cols,data_types=data_types)
            logger.info(update_data_dict)
            data_dict.update(update_data_dict)
            line = line_write_formatter.format(**data_dict)
            print(line,file=OF,flush=True)# flush is necessary
            time.sleep(delay_time)

if __name__ == "__main__":
    fire.Fire(main) # 利用fire命令行化